package com.azxcrm.project.system.customer.controller;

import java.text.ParseException;
import java.util.List;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.azxcrm.common.utils.DateUtils;
import com.azxcrm.common.utils.RandomUtils;
import com.azxcrm.common.utils.security.ShiroUtils;
import com.azxcrm.framework.web.controller.BaseController;
import com.azxcrm.framework.web.domain.Message;
import com.azxcrm.framework.web.page.TableDataInfo;
import com.azxcrm.project.system.basic.dao.IOrderDispatchDao;
import com.azxcrm.project.system.basic.domain.CustomerClueCommunication;
import com.azxcrm.project.system.basic.domain.OrderDispatch;
import com.azxcrm.project.system.basic.domain.OrderModifyRecord;
import com.azxcrm.project.system.basic.service.ICustomerClueCommunicationService;
import com.azxcrm.project.system.basic.service.IOrderModifyRecordService;
import com.azxcrm.project.system.customer.domain.CustomerAttendance;
import com.azxcrm.project.system.customer.domain.CustomerClue;
import com.azxcrm.project.system.customer.domain.CustomerInfo;
import com.azxcrm.project.system.customer.service.ICustomerAttendanceService;
import com.azxcrm.project.system.customer.service.ICustomerClueService;
import com.azxcrm.project.system.customer.service.ICustomerInfoService;
import com.azxcrm.project.system.dict.domain.DictData;
import com.azxcrm.project.system.dict.service.IDictDataService;
import com.azxcrm.project.system.order.domain.Order;
import com.azxcrm.project.system.order.service.IOrderService;
import com.azxcrm.project.system.product.domain.ProductInfo;
import com.azxcrm.project.system.product.service.IProductInfoService;

/**
 * 客户线索 控制层处理
 * 
 * @author Dustyone
 * @date 2018-09-05
 */
@Controller
@RequestMapping("/module/customerClue")
public class CustomerClueController extends BaseController
{
	/**
     * 字典产品类型
     */
    @Value("${crm.dictionary.product.type.orign}")
    private String productType;
    
    /**
     * 字典客户背景
     */
    @Value("${crm.dictionary.customer.background}")
    private String background;
    
    /**
     * 字典客户职业
     */
    @Value("${crm.dictionary.customer.job}")
    private String job;
    
    /**
     * 字典线索渠道
     */
    @Value("${crm.dictionary.clue.channel}")
    private String channel;
    
    /**
     * 字典键值乐享旅游
     */
    @Value("${crm.dictionary.product.type.tourismr}")
    private String tourismr;
    
    /**
     * 字典键值康复项目
     */
    @Value("${crm.dictionary.product.type.recure}")
    private String recure;
    
    /**
     * 字典常见问题类型
     */
    @Value("${crm.dictionary.question.type}")
    private String sys_question_type;
    
   /**
    * 字典客户学历
    */
    @Value("${crm.dictionary.customer.education}")
    private String education;
	
    private String prefix = "module/customerClue";
	
	@Autowired
	private ICustomerClueService customerClueService;
	
	@Autowired
	private IDictDataService dictDataService;
	
	@Autowired
	private IProductInfoService productInfoService;
	
	@Autowired
	private ICustomerInfoService customerInfoService;
	
	@Autowired
	private ICustomerAttendanceService customerAttendanceService;
	
	@Autowired
	private ICustomerClueCommunicationService clueCommunicationService;
	
	@Autowired
	private IOrderService orderService;
	
	@Autowired
	private IOrderDispatchDao orderDispatchDao;
	
	@Autowired
	private IOrderModifyRecordService orderModifyRecordService;
	
	@GetMapping()
	@RequiresPermissions("module:customerClue:view")
	String customerClue()
	{
	    return prefix + "/customerClue";
	}
	
	/**
	 * 查询客户线索列表
	 */
	@GetMapping("/list")
	@RequiresPermissions("module:customerClue:list")
	@ResponseBody
	public TableDataInfo list(CustomerClue customerClue)
	{
		setPageInfo(customerClue);
        List<CustomerClue> list = customerClueService.selectCustomerClueList(customerClue);
		return getDataTable(list);
	}
	
	@GetMapping("offLine")
	@RequiresPermissions("module:customerClueOffLine:view")
	public String underLine()
	{
	    return prefix + "/customerClueOffLine";
	}
	
	/**
	 * 查询线下客户线索列表
	 */
	@GetMapping("/offLineList")
	@RequiresPermissions("module:customerClue:offLinelist")
	@ResponseBody
	public TableDataInfo underLineList(CustomerClue customerClue)
	{
		setPageInfo(customerClue);
		customerClue.setClueSource(4);
        List<CustomerClue> list = customerClueService.selectCustomerClueList(customerClue);
		return getDataTable(list);
	}
	
	/**
	 * 客户详情页条件查询
	 */
	@GetMapping("/switchList")
	@RequiresPermissions("module:customerClue:list")
	@ResponseBody
	public String switchList(CustomerClue customerClue)
	{
		setPageInfo(customerClue);
        List<CustomerClue> list = customerClueService.selectCustomerClueList(customerClue);
        String jsonString = JSON.toJSONString(list);
		return jsonString;
	}
	
	/**
	 * 新增客户线索
	 */
	@GetMapping("/add")
	@RequiresPermissions("module:customerClue:add")
	public String add(Model model,Integer customerId)
	{
		//商品类型
		List<DictData> productList = dictDataService.selectDictDataByDictType(productType);
		model.addAttribute("productList", productList);
		
		//客户背景
		List<DictData> backgroundList = dictDataService.selectDictDataByDictType(background);
		model.addAttribute("backgroundList", backgroundList);
		
		//客户工作
		List<DictData> jobList = dictDataService.selectDictDataByDictType(job);
		model.addAttribute("jobList", jobList);
		
		//客户学历
		List<DictData> educationList = dictDataService.selectDictDataByDictType(education);
		model.addAttribute("educationList", educationList);
		
		//线索渠道
		List<DictData> channelList = dictDataService.selectDictDataByDictType(channel);
		model.addAttribute("channelList", channelList);
		
		//旅游产品
		DictData tourismList = dictDataService.selectDictDataBydictValue(tourismr);
		List<ProductInfo> tourismInfoList = productInfoService.selectProductInfoByTypeId(tourismList.getDictCode().intValue());
		model.addAttribute("tourismInfoList", tourismInfoList);
		
		//康复产品
		DictData recureList = dictDataService.selectDictDataBydictValue(recure);
		List<ProductInfo> recureInfoList = productInfoService.selectProductInfoByTypeId(recureList.getDictCode().intValue());
		model.addAttribute("recureInfoList", recureInfoList);
		
		//真实客户信息新增
		CustomerInfo customerInfo = customerInfoService.selectCustomerInfoById(customerId);
		model.addAttribute("customerInfo", customerInfo);
		
	    return prefix + "/add";
	}
	
	/**
	 * 客户线索详情页面
	 */
	@GetMapping("/details/{clueId}")
	public String details(@PathVariable("clueId") Integer clueId, Model model)
	{
		//客户线索查询
		CustomerClue customerClue = customerClueService.selectCustomerClueById(clueId);
		model.addAttribute("customerClue", customerClue);
		
		//查询客户信息
		CustomerInfo customerInfo = customerInfoService.selectCustomerCellPhone(customerClue.getCustomerCellphone());
		model.addAttribute("customerInfo", customerInfo);
		
		//查询客户参课记录
		List<CustomerAttendance> customerAttendance = customerAttendanceService.selectCustomerAttendanceByCellphone(customerClue.getCustomerCellphone());
		model.addAttribute("customerAttendanceList", customerAttendance);
		
		//预约记录
		List<CustomerClue> list = customerClueService.selectCustomerClueByPhone(customerClue.getCustomerCellphone());
		model.addAttribute("bespeakList", list);
		
		//常见客户类型
		List<DictData>  question = dictDataService.selectDictDataByDictType(sys_question_type);
		model.addAttribute("questionList", question);  
		
		//商品类型
		List<DictData> productList = dictDataService.selectDictDataByDictType(productType);
		model.addAttribute("productList", productList);
		
		//客服接待记录
		CustomerClueCommunication customerClueCommunication = clueCommunicationService.selectCustomerClueCommunicationByClueId(clueId);
		model.addAttribute("customerClueCommunication", customerClueCommunication);
		
		//派单记录
		Order order = new Order();
		order.setClueId(clueId);
		Order or = orderService.selectOrderByOrder(order);
		if(null != or) {
			List<OrderDispatch> dispatch = orderDispatchDao.selectOrderDispatchByOrderId(or.getOrderId());
			model.addAttribute("dispatch", dispatch);
		}else {
			model.addAttribute("dispatch", 1);
		}
	    return prefix + "/details";
	}
	
	/**
	 * 线下客户线索详情页面
	 */
	@GetMapping("/offLineDetails/{clueId}")
	public String offLineDetails(@PathVariable("clueId") Integer clueId, Model model)
	{
		//客户线索查询
		CustomerClue customerClue = customerClueService.selectCustomerClueById(clueId);
		model.addAttribute("customerClue", customerClue);
		
		//查询客户信息
		CustomerInfo customerInfo = customerInfoService.selectCustomerCellPhone(customerClue.getCustomerCellphone());
		model.addAttribute("customerInfo", customerInfo);
		
		 return prefix + "/offLineDetails";
	}
	
	/**
	 * 客户线索详情页面提交
	 * @throws ParseException 
	 */
	@ResponseBody
	@PostMapping("/detailsSave")
	@RequiresPermissions("module:customerClue:add")
	public Message detailsSave(CustomerClue customerClue) throws ParseException {
		
		//沟通记录查询
		CustomerClueCommunication customerClueCommunication = clueCommunicationService.selectCustomerClueCommunicationByClueId(customerClue.getClueId());
		//判断是否创建订单
		if(customerClue.getClueOperationType() == 1){
			Order order = new Order();
			order.setClueId(customerClue.getClueId());
			order.setCreateBy(ShiroUtils.getLoginName());
			order.setOrderType(0);
			order.setServiceUserId(ShiroUtils.getUserId().intValue());
			order.setServiceUserName(ShiroUtils.getLoginName());
			order.setTypeId(customerClueCommunication.getTypeId());
			order.setTypeName(customerClueCommunication.getTypeName());
			int a = RandomUtils.randomCommon(0, 9, 5);
			String time = DateUtils.getDateStamp(); 
			order.setOrderNum("azx"+time+""+a+"");	
			order.setOrderStatus(0);
			orderService.saveOrder(order);
			//记录订单操作
			OrderModifyRecord orderModify = new OrderModifyRecord();
			orderModify.setOrderId(order.getOrderId());
			orderModify.setModifyUserId(ShiroUtils.getUserId().intValue());
			orderModify.setModifyType(3);
			orderModify.setModifyRecod("创建订单");
			orderModifyRecordService.saveOrderModifyRecord(orderModify);
		}
		if (customerClueService.saveCustomerClue(customerClue) > 0)
		{
			return Message.ok();
		}
		return Message.error();
	}
	
	/**
	 * 沟通记录新增
	 */
	@ResponseBody
	@PostMapping("/communicateSave")
	@RequiresPermissions("module:customerClue:add")
	public Message communicateSave(CustomerClueCommunication customerClueCommunication) {
		if (clueCommunicationService.saveCustomerClueCommunication(customerClueCommunication) > 0)
		{
			return Message.ok();
		}
		return Message.error();
	}
	
	/**
	 * 新增客户线索
	 */
	@GetMapping("/queryAdd")
	@RequiresPermissions("module:customerClue:add")
	public String queryAdd()
	{
	    return prefix + "/queryAdd";
	}

	/**
	 * 修改客户线索
	 */
	@GetMapping("/edit/{clueId}")
	@RequiresPermissions("module:customerClue:edit")
	public String edit(@PathVariable("clueId") Integer clueId, Model model)
	{
		//商品类型
		List<DictData> productList = dictDataService.selectDictDataByDictType(productType);
		model.addAttribute("productList", productList);
		
		//线索渠道
		List<DictData> channelList = dictDataService.selectDictDataByDictType(channel);
		model.addAttribute("channelList", channelList);
		
		//客户工作
		List<DictData> jobList = dictDataService.selectDictDataByDictType(job);
		model.addAttribute("jobList", jobList);
		
		//客户学历
		List<DictData> educationList = dictDataService.selectDictDataByDictType(education);
		model.addAttribute("educationList", educationList);
		
		CustomerClue customerClue = customerClueService.selectCustomerClueById(clueId);
		model.addAttribute("customerClue", customerClue);
		
		//客户背景
		List<DictData> backgroundList = dictDataService.selectDictDataByDictType(background);
		model.addAttribute("backgroundList", backgroundList);
		
		//旅游产品
		DictData tourismList = dictDataService.selectDictDataBydictValue(tourismr);
		List<ProductInfo> tourismInfoList = productInfoService.selectProductInfoByTypeId(tourismList.getDictCode().intValue());
		model.addAttribute("tourismInfoList", tourismInfoList);
		
		//康复产品
		DictData recureList = dictDataService.selectDictDataBydictValue(recure);
		List<ProductInfo> recureInfoList = productInfoService.selectProductInfoByTypeId(recureList.getDictCode().intValue());
		model.addAttribute("recureInfoList", recureInfoList);
		
	    return prefix + "/edit";
	}
	
	/**
	 * 保存客户线索
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("module:customerClue:save")
	public Message save(CustomerClue customerClue)
	{
		if (customerClueService.saveCustomerClue(customerClue) > 0)
		{
			return Message.ok();
		}
		return Message.error();
	}
	
	/**
	 * 删除客户线索
	 */
	@PostMapping( "/remove/{clueId}")
	@ResponseBody
	@RequiresPermissions("module:customerClue:remove")
	public Message remove(@PathVariable("clueId") Integer clueId)
	{	
		if(orderService.checkCustomerClueCasecaded(clueId)){
			//如果该线索被引用过不予以被删除
			return Message.error(1, "该线索已被引用,不允许删除");
		}
		
		if (customerClueService.deleteCustomerClueById(clueId) > 0)
		{
		    return Message.ok();
		}
		return Message.error();
	}
	
	/**
	 * 批量删除客户线索
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("module:customerClue:batchRemove")
	public Message remove(@RequestParam("ids[]") Integer[] clueIds)
	{	
		for(int i = 0;i<clueIds.length;i++){
			if(orderService.checkCustomerClueCasecaded(clueIds[i])){
				CustomerClue customerClue = customerClueService.selectCustomerClueById(clueIds[i]);
				//如果该工作流被应用过不予以被删除
				return Message.error(1, "该客户线索 号 ["+customerClue.getClueId()+"] 已被引用,不允许删除");
			}
		}
		
		int rows = customerClueService.batchDeleteCustomerClue(clueIds);
		if (rows > 0)
        {
            return Message.ok();
        }
        return Message.error();
	}
	
	/**
	 * 通过手机号查询客户是否存在
	 */
	@GetMapping( "/queryPhone")
	@ResponseBody
	public String queryPhone(@RequestParam("customerCellphone") String customerCellphone)
	{
		CustomerInfo customerInfo = customerInfoService.selectCustomerCellPhone(customerCellphone);
		String jsonString = JSON.toJSONString(customerInfo);
		return jsonString;
	}
	
}
